import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getProfile, getUserDetailById } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: getToken() || null,
    userInfo: {}
  },
  // 修改状态
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken // 设置token
      setToken(newToken)
    },
    // 删除token
    removeToken(state) {
      state.token = null // 删除vuex的token
      removeToken()
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, obj) {
      console.log('action userLogin', context, obj)
      const res = await login(obj)
      context.commit('setToken', res.data)
    },
    async getUserInfo(context) {
      const result = await getProfile()
      console.log(result, '获取用户信息')
      const info = await getUserDetailById(result.data.userId)
      console.log(info.data, '获取用户详情')
      context.commit('setUserInfo', { ...result.data, ...info.data })
    },
    // 封装用来退出的token
    logout(context) {
      context.commit('removeUserInfo')
      context.commit('removeToken')
    }
  }
}
